<template>
  <!-- 主评论 -->
  <div
    v-if="!isReply"
    class="comment-item"
    @click.stop="$emit('select', comment)"
  >
    <div class="comment-avatar-box">
      <img :src="comment.avatar" class="comment-avatar" />
      <div class="comment-body">
        <div class="comment-header">
          <div class="user-info-horizontal">
            <div class="user-line">
              <span class="username">
                {{ comment.username }}
                <span v-if="comment.isAuthor" class="author-tag">作者</span>
              </span>
            </div>
            <span class="time">{{ formatTime(comment.commentTime) }}</span>
          </div>
          <div class="comment-footer" :class="{ liked: comment.isLiked }">
            <img
              :src="comment.isLiked ? likeBlack : likeWhite"
              class="like-icon"
              @click.stop="$emit('like', comment)"
            />
            <span class="like-count">{{ comment.commentLikesCount }}</span>
            <el-dropdown
              trigger="click"
              @command="(command) => handleMenuCommand(command, comment)"
            >
              <span class="more-btn">···</span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="report">举报</el-dropdown-item>
                  <el-dropdown-item
                    v-if="comment.commentUserId == uid"
                    command="delete"
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <div class="comment-content">{{ comment.commentContent }}</div>
      </div>
    </div>

    <!-- 子评论容器（仅在有回复时渲染） -->
    <div
      v-if="comment.replies && comment.replies.length"
      class="reply-container"
    >
      <CommentItem
        v-for="reply in comment.replies"
        :key="reply.commentId"
        :comment="reply"
        :is-reply="true"
        @select="$emit('select', $event)"
      />
    </div>
  </div>

  <!-- 子评论（楼中楼） -->
  <div v-else class="reply-container">
    <div class="reply-line" @click.stop="$emit('select', comment)">
      <span class="reply-user">
        {{ comment.username }}
        <span v-if="comment.isAuthor" class="author-tag">作者</span>
        回复{{ comment.targetUsername || '未知用户' }} :
      </span>
      <span class="reply-content">{{ comment.commentContent }}</span>
      <span class="reply-time">{{ formatTime(comment.commentTime) }}</span>
      <el-dropdown
        trigger="click"
        @command="(command) => handleMenuCommand(command, comment)"
      >
        <span class="more-btn">···</span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="report">举报</el-dropdown-item>
            <el-dropdown-item
              v-if="comment.commentUserId == uid"
              command="delete"
            >
              删除
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 嵌套 replies -->
    <div
      class="nested-comments"
      v-if="comment.replies && comment.replies.length"
    >
      <CommentItem
        v-for="reply in comment.replies"
        :key="reply.commentId"
        :comment="reply"
        :is-reply="true"
        @select="$emit('select', $event)"
      />
    </div>
  </div>

  <!-- 举报弹窗 -->
  <ReportDialog v-model="showReportDialog" @submit="handleReportSubmit" />
  <teleport to="body">
    <div v-if="showDeleteDialog" class="custom-dialog-mask">
      <div class="custom-dialog">
        <p class="dialog-text">你确定要删除这条评论吗？</p>
        <div class="dialog-buttons">
          <button class="confirm-btn" @click="confirmDeleteComment">
            确认
          </button>
          <button class="cancel-btn" @click="cancelDeleteComment">取消</button>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { ref } from 'vue'
import CommentItem from './CommentItem.vue'
import ReportDialog from '@/components/ReportDialog.vue'
import { reportTarget } from '@/apis/report'
import { ElMessage } from 'element-plus'
import likeBlack from '@/assets/imgs/like-black.png'
import likeWhite from '@/assets/imgs/like-white.png'
import dayjs from 'dayjs'
import { useAccountStore } from '@/stores/useAccountStore'
import { deleteComment } from '@/apis/comment'
const showReportDialog = ref(false)
const reportTargetData = ref({
  targetId: 0,
  targetType: 3, // 子评论
})

const accountStore = useAccountStore()
const uid = accountStore.uid

const showDeleteDialog = ref(false)
const commentToDelete = ref(null)

// 处理菜单命令
const handleMenuCommand = (command, comment) => {
  if (command === 'report') {
    reportTargetData.value.targetId = comment.commentId
    showReportDialog.value = true
  } else if (command === 'delete') {
    commentToDelete.value = comment
    showDeleteDialog.value = true
  }
}

const confirmDeleteComment = async () => {
  try {
    const res = await deleteComment(commentToDelete.value.commentId)
    if (res.code === '200') {
      ElMessage.success('评论删除成功')
      showDeleteDialog.value = false
      // ❗️可以触发父组件刷新评论列表（通过 emit 或者 props）
      location.reload() // 或 emit('refresh') 根据结构决定
    } else {
      ElMessage.error('删除失败，请稍后再试')
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('网络错误，删除失败')
  }
}

const cancelDeleteComment = () => {
  showDeleteDialog.value = false
}

// 处理举报提交
const handleReportSubmit = async (payload) => {
  try {
    const finalData = { ...payload, ...reportTargetData.value }
    await reportTarget(finalData) // 调用举报 API
    ElMessage.success('举报成功，感谢你的反馈')
  } catch (err) {
    console.error(err)
    ElMessage.error('举报失败，请稍后重试')
  }
}

defineProps({
  comment: Object,
  isReply: Boolean,
})

defineEmits(['like', 'select'])

const formatTime = (time) => {
  const now = dayjs()
  const commentTime = dayjs(time)
  const diffMinutes = now.diff(commentTime, 'minute')
  if (diffMinutes < 1) return '刚刚'
  if (diffMinutes < 60) return `${diffMinutes}分钟前`
  if (diffMinutes < 1440) return `${Math.floor(diffMinutes / 60)}小时前`
  return commentTime.format('YYYY-MM-DD')
}
</script>

<style scoped>
/* 评论区 */
.comment-section {
  margin-top: 20px;
}

.comment-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 12px;
}

/* 评论项 */
.comment-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-left: 0;
}

/* 评论者头像和内容 */
.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-avatar-box {
  display: flex;
  gap: 10px; /* 头像与内容间隙 */
}

.comment-body {
  flex: 1;
}

.author-tag {
  font-size: 12px;
  color: #fff;
  background-color: #f39c12;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 6px;
}

/* 评论标题（用户名）和时间 */
.comment-header {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #555;
}

/* 回复者信息：显示“谁回复了谁” */
.user-info-horizontal {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
}

.user-line {
  display: flex;
  align-items: center;
  gap: 6px;
}

.username {
  font-weight: bold;
  font-size: 14px;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
  margin-left: auto; /* 将时间移到最右侧 */
}

/* 回复内容 */
.comment-content {
  font-size: 15px;
  color: #333;
  margin: 8px 0;
}

/* 评论底部按钮 */
.comment-footer {
  font-size: 14px;
  color: #007bff;
  cursor: pointer;
  display: flex;
  gap: 15px;
}

.comment-footer span {
  user-select: none;
}

.comment-footer span:hover {
  text-decoration: underline;
}

.comment-footer.liked {
  color: black; /* 点赞后变黑色 */
}

.like-icon {
  width: 18px;
  height: 18px;
  vertical-align: middle;
  margin-right: 4px;
}

.like-count {
  font-size: 13px;
  color: #999;
}

/* 回复项 */
.reply-item {
  position: relative;
  padding: 8px 0;
}

.reply-target {
  color: #007bff;
  font-weight: 500;
  margin-right: 6px;
}

/* 楼中楼评论项 */
.reply-line {
  display: flex;
  margin-left: 50px; /* 直接缩进50px */
  padding-left: 0;
  padding: 8px 12px;
  border-bottom: 1px solid #eee;
  align-items: center;
}

.reply-line:last-child {
  border-bottom: none;
}

.reply-user {
  font-weight: 600;
  color: #007bff;
  white-space: nowrap;
}

.reply-content {
  flex: 1; /* 占据剩余空间 */
  min-width: 0; /* 允许内容收缩 */
}

/* 时间靠右 */
.reply-time {
  margin-left: auto;
  font-size: 12px;
  color: #999;
  white-space: nowrap;
}

.reply-container {
  border-radius: 8px;
  margin: 8px 0 12px;
  background: #f8f9fa;
  position: relative;
  overflow: hidden;
}

.reply-line:hover {
  background: #f0f6ff !important;
}

.comment-item:hover {
  background: #f0f6ff !important;
}

.selected-comment {
  background: #e6f3ff !important;
  border-radius: 6px;
}

.comment-footer {
  font-size: 14px;
  color: #007bff;
  cursor: pointer;
  display: flex;
  gap: 15px;
  align-items: center;
}

.more-btn {
  font-size: 20px;
  cursor: pointer;
  color: #999;
}
.more-btn:hover {
  color: #0056b3;
}
.custom-dialog-mask {
  position: fixed;
  inset: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 3000;
}

.custom-dialog {
  background-color: white;
  border-radius: 8px;
  padding: 24px;
  width: 280px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

.dialog-buttons {
  margin-top: 16px;
  display: flex;
  justify-content: space-around;
}

.confirm-btn,
.cancel-btn {
  padding: 6px 18px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn {
  background-color: black;
  color: white;
}

.cancel-btn {
  background-color: #909399;
  color: white;
}
</style>
